package springdataredis.demo;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisSentinelConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * redis配置类
 *
 * @author: banjieming
 * @create: 2022-02-19 19:22
 **/
@Configuration
public class RedisConfig {

    //序列化
    @Bean
    public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory){
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        //为string类型的key设置序列化
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        //为string类型的value涉资序列化
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        //为hash类型的key设置序列化
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        //为hash类型的value设置序列化
        redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.setConnectionFactory(lettuceConnectionFactory);
        return redisTemplate;
    }

    @Bean
    public RedisSentinelConfiguration redisSentinelConfiguration(){
        RedisSentinelConfiguration redisSentinelConfiguration =
                new RedisSentinelConfiguration()
                    //主节点名称
                    .master("mymaster")
                    //哨兵
                    .sentinel("192.168.187.129", 26379)
                    .sentinel("192.168.187.129", 26380)
                    .sentinel("192.168.187.129", 26381);

        //设置密码
        redisSentinelConfiguration.setPassword("root");
        return redisSentinelConfiguration;
    }
}
